package com.catchu.pattern.creational.迭代器模式.e随机翻页迭代器.iterator;

import com.catchu.pattern.creational.迭代器模式.e随机翻页迭代器.aggregate.ArrayPayAggregate;
import com.catchu.pattern.creational.迭代器模式.e随机翻页迭代器.model.PayModel;

import java.util.ArrayList;
import java.util.Collection;

public class ArrayIterator implements Iterator {

    /**
     * 用来存放被迭代的数组
     * @return
     */
    private PayModel[] pms;

    public ArrayIterator(ArrayPayAggregate payAggregate) {
        this.pms = payAggregate.getPays();
    }

    /**
     * 迭代的位置索引，从0开始
     */
    private int index = 0;

    @Override
    public boolean hasNext() {
        if(pms!=null && index < pms.length-1){
            return true;
        }
        return false;
    }

    @Override
    public boolean hasPrevious() {
        if(pms!=null && index > 0){
            return true;
        }
        return false;
    }

    @Override
    public Collection getPage(int pageNum, int pageSize) {
        if(pageNum<1){
            throw new RuntimeException("pageNum需大于0");
        }
        Collection result = new ArrayList();
        int start = (pageNum-1) * pageSize;
        int end = start + pageSize - 1;

        //设置最小和最大值
        if(start<0){
            start = 0;
        }
        if(end > pms.length-1){
            end = pms.length-1;
        }

        //设置开始索引
        int index = start;
        while(hasNext() && index <= end){
            result.add(pms[index]);
            index++;
        }

        return result;
    }
}
